package com.h3bpm.web.controller;

import OThinker.Common.Data.Database.Parameter;
import OThinker.Common.Data.DbType;
import OThinker.Common.Organization.Models.Unit;
import OThinker.Common.Organization.Models.User;
import OThinker.H3.Controller.ControllerBase;
import OThinker.H3.Controller.RestfulApi.cloudpivot.ResponseResult;
import com.h3bpm.base.user.UserValidator;
import com.h3bpm.base.util.Sessions;
import com.h3bpm.web.utils.HttpClientUtils;
import com.h3bpm.web.utils.QjcUtils;
import data.DataException;
import data.DataRow;
import data.DataRowCollection;
import data.DataTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RequestMapping("/api/sso")
@RestController
public class SsoController extends ControllerBase {
    private static final Logger log = LoggerFactory.getLogger(SsoController.class);

    @Override
    public String getFunctionCode() {
        return null;
    }

    @Value("${ssoAuthUrl:http://10.50.132.106/TicketCheck.aspx?ticket=}")
    private String oosUrl;
    @Value("${ssoLocal:http://10.50.132.106}")
    private String ssoLocal;


    private ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);

    /**
     * 单点登陆, 弃用了
     *
     * @param ticket
     * @return
     */
    @RequestMapping("auth")
    public ResponseResult test(String ticket) {
        ResponseResult rst = new ResponseResult(-1L, "", null);

        if (ticket != null) {

            if (log.isDebugEnabled()) {

                log.debug("oosUrl ={},ticket={}", oosUrl, ticket);
            }

            String url = oosUrl.concat(ticket);

            try {
                String result;

                result = HttpClientUtils.doGet(url);

                if (log.isDebugEnabled()) {
                    log.debug("票据校验结果:{}", result);
                }


                if (result != null) {
                    User user = getEngine().getOrganization().GetUserByCode(result);

                    Map<String, Object> map = new HashMap<>();

                    map.put("code", user.getCode());
                    map.put("pwd", user.getPassword());


                    rst.setErrcode(0l);

                    rst.setData(map);


                } else {
                    rst.setErrmsg("票据验证失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
                rst.setErrmsg("系统异常");
            }

        } else {
            rst.setErrmsg("ticket is null");
        }


        return rst;
    }

    /**
     * 单点登陆 ,及代办访问处理
     *
     * @param ticket
     * @param redirect
     * @param link
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("ssoAuth")
    public Object ssoAuth(String ticket, String redirect, String link, HttpServletRequest request, HttpServletResponse response) {
        ResponseResult rst = new ResponseResult(-1L, "", null);

        if (log.isDebugEnabled()) {
            log.debug("redirect ={},ticket={},link={}", redirect, ticket, link);
        }
        if (ticket != null) {

            String url = oosUrl.concat(ticket);

            try {
                String result;

                UserValidator userValidator = super.getUserValidator();
                User user = null;
                // 检查是否已登陆
                if (userValidator != null && (user = userValidator.getUser()) != null) {
                    result = user.getCode();
                } else {
                    //通过 票据验证登陆
                    result = HttpClientUtils.doGet(url);
                }

                log.info("票据校验结果:{}", result);

                if (result != null) {
                    if (user == null) {
                        // 第一次 登陆验证 , 把用户放到session 里
                        user = getEngine().getOrganization().GetUserByCode(result);
                        ssoSession(request, user);
                    }

                    rst.setErrcode(0l);
                    rst.setErrmsg("登陆成功");

                    if (redirect != null) {
                        // 单点登陆重定向
                        response.sendRedirect(redirect);
                    } else if (link != null) {
                        // 代办 重定向
                        response.sendRedirect(link);
                        //是预警提醒链接,提醒释放
                        earlySf(link);

                    }

                } else {
                    rst.setErrmsg("票据验证失败");
                }
            } catch (Exception e) {
                e.printStackTrace();
                rst.setErrmsg("系统异常");
            }

        } else {
            rst.setErrmsg("ticket is null");
        }


        return rst;
    }


    /**
     * 预警释放
     */
    private void earlySf(String link) {
        final String id = QjcUtils.getParamByUrl(link,"InstanceId");

        if (id != null) {
            fixedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        String sql = "update early_warning set isRead = 1 WHERE id = '%s'";
                        int i = getEngine().getPortalQuery().ExcuteNoQuery(String.format(sql, id));
                        System.out.printf("收付款预警 修改为已读成功");
                    } catch (Exception e) {
                        System.out.printf("收付款预警 修改为已读失败");
                    }

                }
            });
        }

    }

    /**
     * 获取代办
     *
     * @param request
     * @param code
     * @return
     */
    @RequestMapping("workItem")
    public Object workItem(HttpServletRequest request, String code) {

//        log.info("获取代办参数code={}", code);
        String xml;
        try {
            User user = getEngine().getOrganization().GetUserByCode(code);
             if (user==null){
                throw  new Exception("用户不存在,code="+code);
             }
//            ssoSession(request, user);

            String sql = "SELECT otw.displayName,oic.instanceName,DATE_FORMAT(otw.startTime,'%Y-%m-%d') as startTime ,otw.participantName,otw.objectId from ot_workitem otw " +
                    "left join ot_instancecontext oic on otw.InstanceId = oic.ObjectID " +
                    "where otw.participant = '${participant}'";

            sql = sql.replace("${participant}", user.getObjectId());
            DataTable dataTable = getEngine().getPortalQuery().QueryTable(sql);

            xml = beanToXml(dataTable,getEarlyList(user.getObjectID()));

//            if (log.isDebugEnabled()) {
//                log.debug("代码xml={}", xml);
//            }


        } catch (Exception e) {

            log.info(e.getMessage(), e);
            xml = "系统异常";
        }


        return xml;
    }

    // 添加预提醒的
    private StringBuilder getEarlyList(String participant) throws  Exception {
        String sql = "SELECT id,usrId,remark, DATE_FORMAT(createTime,'%Y-%m-%d') as createTime from early_warning WHERE isRead = 0 and  usrId = '"+participant+"' ";


        DataTable dataTable = getEngine().getPortalQuery().QueryTable(sql);

        StringBuilder xmlStr = new StringBuilder();
        if (dataTable != null && dataTable.getRows().size() > 0) {

            Unit unit = getEngine().getOrganization().GetUnit(participant);
            String name = unit.getName();

            DataRowCollection rows = dataTable.getRows();
            DataRow dataRow;
            String paramXml = "<todo><senduser>%s</senduser><sendtime>%s</sendtime><subject>%s</subject> <link>%s</link><category></category ></todo>";
            String url = ssoLocal + "/Portal/InstanceSheets.html?InstanceId=%s";
            for (int i = 0; i < rows.size(); i++) {
                dataRow = rows.get(i);

                String  createTime = dataRow.getString("createTime");
                String  usrId = dataRow.getString("usrId");
                String  id = dataRow.getString("id");
                String  remark = dataRow.getString("remark");

                xmlStr.append(String.format(paramXml, name, createTime, remark, String.format(url, id)));
            }


        }
        return xmlStr;

    }


    private void ssoSession(HttpServletRequest request, User user) throws Exception {
        UserValidator userValidator = new UserValidator(getEngine(), user.getObjectId(), null, null);

        request.getSession().setAttribute(Sessions.GetUserValidator(), userValidator);
    }


    private String beanToXml(DataTable dataTable,StringBuilder otherTodo) throws DataException {

        StringBuilder xmlStr = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?><todolist>");
        String paramXml = "<todo><senduser>%s</senduser><sendtime>%s</sendtime><subject>%s</subject> <link>%s</link><category></category ></todo>";

        String url = ssoLocal + "/Portal/WorkItemSheets.html?WorkItemID=%s";
        if (dataTable != null && dataTable.getRows().size() > 0) {
            DataRowCollection rows = dataTable.getRows();
            DataRow dataRow;
            String displayName, instanceName, startTime, participantName, objectId;
            StringBuilder name = new StringBuilder();
            for (int i = 0; i < rows.size(); i++) {
                dataRow = rows.get(i);

                displayName = dataRow.getString("displayName");
                instanceName = dataRow.getString("instanceName");
                startTime = dataRow.getString("startTime");
                participantName = dataRow.getString("participantName");
                objectId = dataRow.getString("objectId");

                name.delete(0, name.length());
                name.append(instanceName).append("-").append(displayName);

                xmlStr.append(String.format(paramXml, participantName, startTime, name, String.format(url, objectId)));

            }

        }

        xmlStr.append(otherTodo);

        xmlStr.append("</todolist>");


        return xmlStr.toString();
    }


    @RequestMapping("appWorkItemCount")
    public Object appWorkItemCount(String username,HttpServletRequest request) {
        ResponseResult rst = new ResponseResult(-1L, "", null);
        Map<String, Integer> stringIntegerHashMap = new HashMap<>(1);
        try {
            log.info("获取代办参数userID={}", username);
            String sql = "SELECT count(1) as count from ot_workitem otw where otw.participant = ? ";
            User user = getEngine().getOrganization().GetUserByCode(username);
            Parameter[] params = new Parameter[1];
            params[0] = new Parameter("Originator", DbType.String, user.getObjectID());
            DataTable dataTable = getEngine().getPortalQuery().QueryTable(sql, params);
            DataRowCollection queryRows = dataTable.getRows();
            if (queryRows != null && queryRows.size() > 0) {
                DataRow dataRow = queryRows.get(0);
                int count = dataRow.getInt("count");
                log.info("获取代办个数workItemCount={}", count);
                stringIntegerHashMap.put("workItemCount", count);
                rst.setErrcode(0L);
                rst.setData(stringIntegerHashMap);
                rst.setErrmsg("执行成功");
            }
            return rst;
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            rst.setErrmsg("系统错误");
        }
        return rst;
    }

    @RequestMapping(value = "/appSsoAuth", method = RequestMethod.GET)
    public Object blockToPortal(String username,String redirect,HttpServletRequest request,HttpServletResponse response) {
        ResponseResult rst = new ResponseResult(-1L, "", null);
        if ("".equals(username) || null == username) {
            rst.setErrmsg("用户为空");
            return rst;
        }
        if (log.isDebugEnabled()) {
            log.debug("userId ={}", username);
        }
        UserValidator userValidator = super.getUserValidator();
        String userCode;
        User user = null;
        try {
            // 检查是否已登陆
            if (userValidator != null && (user = userValidator.getUser()) != null) {
                userCode = user.getCode();
                log.info("userCode ={}", userCode);
            }
            user = getEngine().getOrganization().GetUserByCode(username);
            if (user!=null){
                ssoSession(request, user);
                log.info("userCode ={}", user.getCode());
                response.sendRedirect(redirect);
            }else {
                rst.setErrmsg("此用户不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return rst;
    }

}
